package controllers;

import models.Place;

import org.codehaus.jackson.node.ObjectNode;

import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;

@Security.Authenticated(Secure.class)
public class Places extends Controller {

    static Form<Place> placeForm;

    public static Result index() {
        return ok(views.html.User.Place.index.render());
    }

    public static Result listPlaces() {
        return ok(views.html.User.Place.listPlaces.render(Place.find.all(), session().get("keyId"),
                session().get("vCode")));
    }

    public static Result addPlaceForm(long id) {
        placeForm = Form.form(Place.class);
        // Fill form with values
        if (id > 0) {
            placeForm = placeForm.fill(Place.find.byId(id));
        }
        return ok(views.html.User.Place.addPlace.render(placeForm, ""));
    }

    public static Result addPlace() {
        Form<Place> filledPlaceForm = placeForm.bindFromRequest();

        // Remove wrong errors
        filledPlaceForm.errors().remove("category");

        if (filledPlaceForm.hasErrors()) {
            // Return error if empty fields
            return ok(views.html.User.Place.addPlace.render(filledPlaceForm, ""));
        } else {
            ObjectNode result = Json.newObject();
            result.put("redirect", true);
            Place place = (!filledPlaceForm.field("id").value().isEmpty()) ? Place.find.byId(Long
                    .valueOf(filledPlaceForm.field("id").value())) : new Place();

            place.setAddress(filledPlaceForm.field("address").value());
            place.setCategory("");
            place.setDescription(filledPlaceForm.field("description").value());
            place.setLatitude(filledPlaceForm.field("latitude").value());
            place.setLongitude(filledPlaceForm.field("longitude").value());
            place.setName(filledPlaceForm.field("name").value());

            if (place.getId() == null) {
                place.save();
            } else {
                place.update();
            }
            return ok(result);
        }
    }
}